import logging
import time
from selenium import webdriver
from selenium.webdriver.support.select import Select

from webAutomation import configs
import logging.handlers


# 截图工具
def screenshot(case):
    t = time.strftime("%Y%m%d-%H%M%S")
    img_path = configs.BATH_PATH + "/screenshot/{}-{}".format(case.testMethodName, t)
    return DriverUtil.get_driver().get_screenshot_as_file(img_path)


# 获取弹窗的提示信息
def get_tips_msg(element_class_name):
    msg = DriverUtil.get_driver().find_element_by_class_name(element_class_name).text
    return msg

# 断言新页面有指定文本
def exit_text(text):
    try:
        xpath = "//*[contains(text(),'{}')]".format(text)
        element = DriverUtil.get_driver().find_element_by_xpath(xpath)
        return element is not None
    except Exception as e:
        print("current page don't conains {}".format(text))
        logging.exception("断言的异常日志为：{}".format(e))
        return False

# 浏览器驱动对象工具
class DriverUtil:
    driver = None
    auto_quit = True

    # 获取浏览器驱动对象
    @classmethod
    def get_driver(cls):
        if cls.driver is None:
            # 输出日志
            logging.info("init driver")
            # 创建浏览器驱动对象
            cls.driver = webdriver.Chrome()
            # 使浏览器窗口最大化
            cls.driver.maximize_window()
            # 隐式等待，最长等待20S
            cls.driver.implicitly_wait(20)
            # 连接服务器地址
            cls.driver.get("http://192.168.1.173:8080/login")
        return cls.driver

    # 关闭浏览器驱动对象
    @classmethod
    def quit_driver(cls):
        if cls.driver and cls.auto_quit:
            cls.driver.quit()
            cls.driver = None

    # 设置自动退出浏览器驱动
    @classmethod
    def set_auto_quit(cls, auto_quit):
        cls.auto_quit = auto_quit


# 日志初始化
def log_init():
    # 创建日志器对象
    logger = logging.getLogger()

    # 设置日志器级别
    logger.setLevel(logging.INFO)

    # 创建处理器对象
    # 控制台处理器
    sh = logging.StreamHandler()
    # 文本处理器
    log_file = configs.BATH_PATH + "/log/P2P.log"
    fh = logging.handlers.TimedRotatingFileHandler(log_file,
                                                   when="midnight",
                                                   interval=1,
                                                   backupCount=7,
                                                   encoding="UTF-8")

    # 创建格式化器对象
    fmt = "%(asctime)s %(levelname)s [%(name)s] [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
    formatter = logging.Formatter(fmt)

    # 将格式化器对象添加到处理器对象
    sh.setFormatter(formatter)
    fh.setFormatter(formatter)

    # 将处理器对象添加到日志器对象
    logger.addHandler(sh)
    logger.addHandler(fh)
